<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      
      <el-input 
      clearable 
      @keyup.enter.native="handleFilter" 
      v-model="listQuery.equipmentId" style="width: 200px;margin-right:15px;" class="filter-item" 
      :placeholder="$t('device.equipmentId')" > 
      </el-input>
      <el-input 
      clearable 
      @keyup.enter.native="handleFilter" 
      v-model="listQuery.equipmentNumber" style="width: 200px;margin-right:15px;" class="filter-item" 
      :placeholder="$t('device.equipmentNumber')" > 
      </el-input>
      <el-input 
      clearable 
      @keyup.enter.native="handleFilter" 
      v-model="listQuery.businessName" 
      style="width: 200px;margin-right:15px;" class="filter-item" 
      :placeholder="$t('device.Shop_name')" > 
      </el-input>
      <div style="display:flex;justify-content:space-betweem">
        <el-input clearable type="number" @keyup.enter.native="handleFilter" v-model="listQuery.startTime" style="width: 200px;margin-right:15px;" class="filter-item" 
        :placeholder="$t('device.Minimum_usage_time')" > 
        </el-input>
        -
        <el-input clearable type="number" @keyup.enter.native="handleFilter" v-model="listQuery.endTime" style="width: 200px;margin-left:15px;" class="filter-item" 
        :placeholder="$t('device.Maximum_usage_time')" > 
         </el-input>
      </div>
     
      <el-date-picker
        v-model="listQuery.regisTime"
        :start-placeholder="$t('device.Minimum_registration_time')"
        :end-placeholder="$t('device.Maximum_registration_time')"
        type="datetimerange"
        :placeholder="$t('recharge.Select_date')"
        value-format="timestamp"
        style="margin-right:20px;">
      </el-date-picker>
      <el-button  type="primary" v-waves icon="el-icon-search" @click="handleFilter">{{$t('device.Find')}}</el-button>
      <el-button type="primary"  v-waves icon="el-icon-circle-plus-outline" @click="dialog.add = true" >{{$t('device.Add')}}</el-button>
      <el-button  type='primary' v-waves   icon="el-icon-upload" @click='uploadBtn'  :loading="uploadLoading">{{$t('device.Import')}}</el-button>
      <el-button  type='primary' v-waves   @click="handleDownload"  icon="el-icon-download"  :loading="downloadLoading">{{$t('device.Export')}}</el-button>
    </div>
    <!-- table 表格 -->
    <el-table  :data="list" v-loading="loading.list" :element-loading-text="$t('common.Loading')" border fit highlight-current-row
      style="width: 100%">
      <el-table-column  :label="$t('device.equipmentId')" prop='equipmentId' />
      <el-table-column  :label="$t('device.Device_serial_number')" prop='equipmentNumber' />
      <el-table-column  :label="$t('device.Cabinet_name')" prop='equipmentName' />
      <el-table-column  :label="$t('device.Model')" prop='slotSum' />
      <el-table-column  :label="$t('device.Shop_name')" prop='businessName' />
      <el-table-column  :label="$t('device.Location')" prop='area' />
      <el-table-column  :label="$t('device.Address')" prop='address' />
      <el-table-column  :label="$t('device.Accumulated_using_time')" prop='hourage' />
      <el-table-column  :label="$t('device.Registration_Date')">
         <template slot-scope="scope">
           {{scope.row.ctime | parseTime}}
        </template>
      </el-table-column>
      <el-table-column  :label="$t('device.Charging_standard')">
         <template slot-scope="scope">
           {{scope.row.unitPrice ? scope.row.unitPrice : '-' }}
        </template>
      </el-table-column>
      <el-table-column  :label="$t('device.Accumulated_revneue')">
         <template slot-scope="scope">
           {{scope.row.sumPrice ? `${scope.row.sumPrice}${$t('device.unit')}` : `0${$t('device.unit')}`}}
        </template>
      </el-table-column>
      <el-table-column  :label="$t('device.Cabinet_information')"  class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button  type='text' @click="getEquipmentParam(scope.row)">{{$t('device.View')}}</el-button>
        </template>
      </el-table-column>
      <el-table-column  :label="$t('device.Operate')"  class-name="small-padding">
        <template slot-scope="scope">
          <div class="fy" v-if="scope.row.isBinding == 1">
            <el-button  @click="showBindDialog(scope.row)" v-if="scope.row.isBinding == 1" type='primary'>{{$t('device.Bound')}}</el-button>
            <el-button type="danger" @click='delEquipent(scope.row)'>{{$t('device.Delete')}}</el-button>
          </div>
          <div class="fy" v-else>
            <el-button type='primary' size='small' @click="getEquipmentInfo(scope.row, 1)">{{$t('device.Divided_into_settings')}}</el-button>
            <el-button type='primary' @click="getEquipmentInfo(scope.row, 2)">{{$t('device.Charge_setting')}}</el-button>
            <el-button type="danger" @click='unBind(scope.row)'>{{$t('device.Untied')}}</el-button>
            <el-button type="danger" @click='delEquipent(scope.row)'>{{$t('device.Delete')}}</el-button>      
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination 
      background 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" 
      :current-page="listQuery.pageNo" 
      :page-sizes="[10, 20, 30, 40]" 
      :page-size="listQuery.pageSize" 
      layout="total, sizes, prev, pager, next, jumper" 
      :total="total">
      </el-pagination>
    </div>
    <!-- 新增弹框 -->
    <el-dialog :title="$t('device.add_Cabinet')" :visible.sync="dialog.add">
      <el-form :model="addQuery" :rules='addRules' ref="addForm"  label-position="right" label-width="120px"> 
        <el-form-item :label="$t('device.Device_serial_number')" prop="equipmentNumber">
         <el-input  clearable v-model="addQuery.equipmentNumber" :placeholder="$t('device.Device_serial_number')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('device.Cabinet_name')" prop="equipmentName">
         <el-input  clearable v-model="addQuery.equipmentName" :placeholder="$t('device.Cabinet_name')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('device.Model')" prop="slotSum">
         <el-input type="number"  clearable v-model="addQuery.slotSum" :placeholder="$t('device.Model')"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.add = false">{{$t('device.Cancel')}}</el-button>
        <el-button type="primary" :loading="loading.add" @click="add">{{$t('device.Submit')}}</el-button>
      </div>
    </el-dialog>
    <!-- 绑定弹框 -->
    <el-dialog title="绑定机柜" :visible.sync="dialog.bind">
      <el-form :model="bindQuery" :rules='bindRules' ref="bindForm"  label-position="right" label-width="120px"> 
        <el-form-item label="商户id" prop="businessId">
         <el-input  clearable v-model="bindQuery.businessId" placeholder="商户id"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.bind = false">取消</el-button>
        <el-button type="primary" :loading="loading.bind" @click="bindingEquipment">确定</el-button>
      </div>
    </el-dialog>
    <!-- 基本信息弹框 -->
    <el-dialog :title="$t(basicTitle)"  :visible.sync="dialog.basic">
      <div v-if="basicType == 1">
        <el-form :model="profitQuery" ref="basicForm"  label-position="right" label-width="120px"> 
          <el-form-item :label="$t('device.Provincial_agent')" >
            <el-input type="number"  v-model="profitQuery.provinceCommission" :placeholder="$t('device.Provincial_agent')"></el-input> %
          </el-form-item>
          <el-form-item :label="$t('device.City_agent')" >
            <el-input type="number"   v-model="profitQuery.cityCommission" :placeholder="$t('device.City_agent')"></el-input> %
          </el-form-item>
          <el-form-item :label="$t('device.Channel_distributor')"> 
            <el-input type="number"  v-model="profitQuery.placeCommission" :placeholder="$t('device.Channel_distributor')"></el-input> %
          </el-form-item>
          <el-form-item :label="$t('device.Merchant_sharing')">
            <el-input type="number"  v-model="profitQuery.businessCommission" :placeholder="$t('device.Merchant_sharing')"></el-input> %
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align:right">
          <el-button @click="dialog.basic = false">{{$t('device.Cancel')}}</el-button>
          <el-button type="primary" :loading="loading.detail" @click="setCommission">{{$t('device.Submit')}}</el-button>
        </div>
      </div>
      <div v-else>
        <el-form :model="priceQuery"  ref="basicForm"  label-position="right" label-width="120px"> 
          <el-form-item :label="$t('device.Price')" >
            <el-input type="number"   v-model="priceQuery.price" :placeholder="$t('device.Price')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('device.Capping_price')" >
            <el-input type="number"   v-model="priceQuery.topPrice" :placeholder="$t('device.Capping_price')"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align:right">
          <el-button @click="dialog.basic = false">{{$t('device.Cancel')}}</el-button>
          <el-button type="primary" :loading="loading.detail" @click="updatePrice">{{$t('device.Submit')}}</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 设备详情弹框 -->
    <el-dialog :title="$t('device.Cabinet_information')" :visible.sync="dialog.detail"  @close='equipmentDetailInfo = null'>
      <div v-loading='loading.detail'>
        <div v-if="equipmentDetailInfo" >
        <div class="form_item">
          <span class="label">{{$t('device.QR_code')}}：</span>
          <img :src="equipmentDetailInfo.QRCode" alt="" style="width:200px;height:200px">
        </div>
        <div class="form_item">
          <span class="label">{{$t('device.useAbleDevice')}}：</span>
          {{equipmentDetailInfo.remainNum}}
        </div>
        <div class="form_item">
          <span class="label">{{$t('device.backDevice')}}：</span>
          {{equipmentDetailInfo.sumNum - equipmentDetailInfo.remainNum}}
        </div>
        <div class="form_item" >
          <div class="label">{{$t('device.Details')}}：</div>
          <div class="_c">
            <div v-for="(item, index) in equipmentDetailInfo.battery" :key="index">
              <div v-if="item" class="e_item">
                <span>{{$t('device.Charging_treasure_ID')}}: {{item.terminalid}}</span>
                <span>{{$t('device.Electricity')}}： {{item.level | batteryLv }}</span>
              </div>
              <div v-else  class="e_item">{{$t('device.Empty_slot')}}</div>
              <el-button style="margin-left:20px" v-if="item" round type="warning" @click="popupEquipent(item)">{{$t('device.Pop_charging')}}</el-button>
              
            </div>
          </div>
        </div>
      </div>
      <div v-else>
        {{$t('device.No_device_information')}}
      </div>  
      </div>
    </el-dialog>
    <!-- 导入excel -->
    <input type="file" @change="uploadExcel" ref='uploadExcel' style="display:none">
    <!-- 回到顶部 -->
    <BackToTop></BackToTop>
  </div>
</template>

<script>
import { 
  getEquipmentList as getList, 
  addEquipment, 
  bindingEquipment,
  getEquipmentParam,
  importing,
  getEquipmentInfo,
  setCommission,
  updatePrice,
  popupEquipent,
  delEquipent
} from '@/api/equipment'
import { validatePhone } from '@/utils/validate'
import { parseTime } from '@/utils'
import BackToTop from '@/components/BackToTop'
export default {
  filters: {
    batteryLv (val) {
      const lvs = [0, 1, 2, 3, 4]
      return (lvs[val] + 1) * 20 + '%'
    }
  },
  components: {
    BackToTop
  },
  name: 'equipment_cabinet',
  data() {
    var validatePass = (rule, value, callback) => {
      if (!validatePhone(value)) {
        return callback(new Error('请填写正确的手机号码'));
      } else {
        callback();
      }
    };
    return {
      total: 0,
      listQuery: {
        pageNo: 1,
        pageSize: 10,
        equipmentId: '',
        equipmentNumber: '',
        businessName:'',
        startTime: '',
        endTime: '',
        regisTime: ''
      },
      list: null,
      loading: {
        list: false,
        add: false,
        bind: false,
        detail: false
      },
      dialog:{
        add:false,
        bind: false,
        detail: false,
        basic: false
      },
      addQuery:{
        equipmentNumber: '',
        equipmentName: '',
        slotSum: ''
      },
      addRules: {
          equipmentNumber: [
            { required: true, message: this.$t('device.Device_serial_number'), trigger: 'blur' }
          ],
          equipmentName: [
            { required: true, message: this.$t('device.Cabinet_name'), trigger: 'blur' }
          ],
          slotSum: [
            { required: true, message: this.$t('device.Model'), trigger: 'blur' }
          ]
      },
      bindQuery:{
        equipmentId: '',
        businessId: ''
      },
      bindRules: {
          businessId: [
            { required: true, message: '请填写商户id', trigger: 'blur' }
          ]
      },
      roleList:[
        {userType:2,name:'维修'},
        {userType:3,name:'保洁'}
      ],
      profitQuery: {
        equipmentId: '',
        provinceCommission: '',
        cityCommission: '',
        placeCommission: '',
        businessCommission: ''
      },
      priceQuery: {
        equipmentId: '',
        price: '',
        topPrice: ''
      },
      downloadLoading: false,
      uploadLoading: false,
      equipmentDetailInfo: null,  // 设备详情
      basicInfo: null, // 设备基础信息
      basicType: 1,
      equipmentNumber: '',
      equipmentId: ''
    }
  },
  methods: {
    // 导入按钮
    uploadBtn () {
      this.$refs.uploadExcel.click()
    },
    // 上传excel
    async uploadExcel (e) {
      this.uploadLoading = true
      try {
        const excel = e.target.files[0]
        const fd = new FormData()
        fd.append('excel', excel)
        const res = await importing(fd)
        if (res.code === 1) {
          this.$message.success('导入成功')
          this.getList()
        }
      } catch (error) {
        this.$refs.uploadExcel.value = ''
        this.uploadLoading = false
      }
      this.uploadLoading = false
       this.$refs.uploadExcel.value = ''
    },
    //导出
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['机柜名称', '型号', '设备序列号','商家名称', '地区', '详细地址','累积使用时间','注册时间','收费标准','累计收入']
        const filterVal = ['equipmentName', 'slotSum', 'equipmentNumber','businessName', 'area', 'address','hourage','ctime', 'unitPrice', 'sumPrice']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '机柜列表'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
      if (j === 'ctime') {
        return parseTime(v[j])
      } else {
        return v[j]
      }
      }))
    },
    //获取用户列表
    async getList() {
      this.loading.list = true
      let { startUseTime, regisTime, ...query } = this.listQuery
      let [startCtime, endCtime] = regisTime ? regisTime : []
      query = Object.assign({}, query, {startCtime, endCtime})
      try {
        const { data } = await getList(query)
        this.list = data.records.map((item, index) => ({
          index: index + 1, 
          ...item,
          slotSum: item.slotSum + '口',
          hourage: item.hourage + '小时',
          unitPrice: item.unitPrice  ? `${item.unitPrice}元/小时` : ''
        }))
        this.total = data.total
      } catch (error) {
        
      }
      this.loading.list = false     
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    // 新增设备
    async add() {
      this.$refs['addForm'].validate(async (valid) => {
          if (valid) {
            this.loading.add = true
            try{
              const res = await addEquipment(this.addQuery)
              if (res.code === 1) {
                this.$message({
                  type:'success',
                  message: '新增成功'
                })
                this.getList()
                this.$refs['addForm'].resetFields();
                this.dialog.add = false
              }
             
            } catch(error) {
              this.loading.add = false
            }
            this.loading.add = false
          } else {
            console.log('error submit!!');
            return false;
          }
        });
     
    },
    // 绑定或者解绑设备
    async bindingEquipment () {
      const res = await bindingEquipment(this.bindQuery)
      if (res.code === 1) {
        this.$message.success('绑定成功')
        this.dialog.bind = false
        this.$refs['bindForm'].resetFields();
        this.getList()
      }
    },
    showBindDialog ({equipmentId, isBinding}) {
      this.bindQuery.equipmentId = equipmentId
      this.bindQuery.type = isBinding
      this.dialog.bind = true
    },
    // 删除机柜
    async delEquipent ({equipmentId}) {
      this.$confirm('确定删除设备?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await delEquipent({equipmentId})
        this.$message.success('删除成功')
        this.getList()
      })
    },
    // 解绑
    unBind ({equipmentId, isBinding}) {
      this.bindQuery.equipmentId = equipmentId
      this.bindQuery.type = isBinding
      this.$confirm('确定解绑设备?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await bindingEquipment(this.bindQuery)
        if (res.code === 1) {
          this.$message.success('解绑成功')
          this.getList()
        }
      
      })
    },
    // 获取机柜信息
    async getEquipmentParam ({equipmentId, equipmentNumber}) {
      this.dialog.detail = true
      this.loading.detail = true
      this.equipmentNumber = equipmentNumber
      this.equipmentId = equipmentId
      try {
        const res = await getEquipmentParam({
          equipmentId: this.equipmentId
        })
        this.loading.detail = false
        if (res.code === 1) {
          this.equipmentDetailInfo = res.data
        }
      } catch (error) {
        this.loading.detail = false
      }
     
    },
    // 获取机柜基本信息
    async getEquipmentInfo ({equipmentId}, type) {
      this.basicType = type
      this.dialog.basic = true
      const res = await getEquipmentInfo({equipmentId})
      if (res.code === 1) {
        if (type === 1) {
          let { provinceCommission, cityCommission, placeCommission, businessCommission } = res.data
          this.profitQuery = Object.assign({}, this.profitQuery, { equipmentId, provinceCommission, cityCommission, placeCommission, businessCommission })
        } else {
          let { unitPrice, topPrice } = res.data
          this.priceQuery = Object.assign({}, this.priceQuery, { equipmentId, price: unitPrice, topPrice })
        }
      }
    },
    // 设置分成
    async setCommission () {
      this.loading.detai = true
      try {
        const res = await setCommission(this.profitQuery)
        if (res.code === 1) {
          this.$message.success('设置成功')
          this.getList()
          this.dialog.basic = false
        }
      } catch (error) {
        this.loading.detai = false
      }
      this.loading.detai = false
    },
    // 修改价格
    async updatePrice () {
      this.loading.detai = true
      try {
        const res = await updatePrice(this.priceQuery)
        if (res.code === 1) {
          this.$message.success('修改成功')
          this.getList()
          this.dialog.basic = false
        }
      } catch (error) {
        this.loading.detai = false
      }
      this.loading.detai = false
    },
    // 弹出充电宝
    async popupEquipent ({slot}) {
      const res = await popupEquipent({equipmentNumber: this.equipmentNumber, slot})
      this.$message.success('弹出成功')
      this.getEquipmentParam({equipmentId: this.equipmentId, equipmentNumber: this.equipmentNumber})
    }
  }, 
  created() {
    this.getList()
  },
  computed: {
    basicTitle () {
      return this.basicType == 1 ? 'device.Divided_into_settings' : 'device.Charge_setting'
    }
  }
}
</script>
<style lang="scss" scoped>
/deep/ .el-form-item__content {
  white-space: nowrap;
}

._c {
  border: 1px solid #000;
  border-radius: 8px;
  padding: 10px;
  display: flex;
  flex-direction: column;
 
  & > div {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
}
.e_item {
  border: 1px solid #000;
  border-radius: 8px;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  flex: 1
}
</style>

